package com.cgly.medical.test;

import com.alibaba.fastjson.JSON;
import com.cgly.medical.domain.Patient;
import com.cgly.medical.mapper.PatientMapper;
import com.cgly.medical.model.PatientModel;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@SpringBootTest
public class testPatient {

    private RestHighLevelClient client;

    @BeforeEach
    void setUp(){
        this.client=new RestHighLevelClient(RestClient.builder(HttpHost.create("http://localhost:9200"))
        );
    }

    @AfterEach
    void tearDowm() throws IOException {
        this.client.close();
    }

    @Resource
    private PatientMapper patientMapper;
    //批量导入文档
    @Test
    void testBulkRequest() throws IOException {
        //批量查询数据
        List<Patient> allPatient = patientMapper.getAllPatient();
        //1.创建request
        BulkRequest request=new BulkRequest();
        //2.准备参数，添加多个新增的request
        //转换为HotelDoc
        for (Patient patient : allPatient) {
            PatientModel patientModel = new PatientModel(patient);
            request.add(new IndexRequest("patient").id(String.valueOf(patientModel.getId())).source(JSON.toJSONString(patientModel), XContentType.JSON));
        }
        //3.发送请求
        client.bulk(request, RequestOptions.DEFAULT);
    }
}
